﻿using System;
using System.Security.Authentication;
using Google.Analytics.Model;
using Google.Analytics.Model.Feeds;
using Google.Analytics.Model.Queries;

namespace Google.Analytics.RemoteAccess.API
{
    public class AnalyticsAPI : IAnalyticsAPI
    {
        private static readonly object staticLock = new object();
        private readonly AuthState state;
        private static AnalyticsService service;

        public AuthState State
        {
            get { return state; }
        }

        /// <summary>
        /// The OAuth service definition for the Google client
        /// </summary>
        private static AnalyticsService Service
        {
            get
            {
                if (service == null)
                    lock (staticLock)
                        if (service == null)
                            service = new AnalyticsService("GoogleAnalytics");

                return service;
            }
        }

        /// <summary>
        /// Creates new instance of the API
        /// </summary>
        /// <param name="state"></param>

        public AnalyticsAPI(AuthState state)
        {
            if (state == null)
                throw new ArgumentNullException("state");

            this.state = state;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public AuthState ForceAuthentication()
        {
            Service.setUserCredentials(State.UserName, State.Password);
            State.QueryAuthenticationToken = Service.QueryAuthenticationToken();
            return State;
        }

        public AccountFeed GetAccounts(AccountQuery accountQuery)
        {
            if(string.IsNullOrEmpty(State.QueryAuthenticationToken))
                throw new InvalidCredentialException(ExceptionText.NullToken);

            return Service.Query(accountQuery) as AccountFeed;
        }

        public DataFeed GetData(DataQuery dataQuery)
        {
            if (string.IsNullOrEmpty(State.QueryAuthenticationToken))
                throw new InvalidCredentialException(ExceptionText.NullToken);

            return Service.Query(dataQuery) as DataFeed;
        }
    }
}
